<template>
  <div class="min-h-screen bg-gradient-to-br from-blue-50 to-purple-50 py-8">
    <div class="max-w-4xl mx-auto px-4 sm:px-6 lg:px-8">
      <!-- Header -->
      <div class="text-center mb-8">
        <h1 class="text-3xl font-bold text-gray-900 mb-4">
          <span class="text-gradient">二维码生成器</span>
        </h1>
        <p class="text-lg text-gray-600">
          快速生成二维码，支持自定义样式和尺寸
        </p>
      </div>

      <!-- Tool Container -->
      <div class="bg-white rounded-xl shadow-lg p-6">
        <div class="grid grid-cols-1 lg:grid-cols-2 gap-8">
          <!-- Left Column: Settings -->
          <div>
            <!-- Input -->
            <div class="mb-6">
              <label class="block text-sm font-medium text-gray-700 mb-2">
                输入内容
              </label>
              <textarea
                v-model="inputText"
                placeholder="请输入要生成二维码的内容..."
                class="textarea-field h-24"
                @input="generateQRCode"
              ></textarea>
              <div class="mt-2 text-sm text-gray-500">
                字符数: {{ inputText.length }}
              </div>
            </div>

            <!-- QR Code Type -->
            <div class="mb-6">
              <label class="block text-sm font-medium text-gray-700 mb-2">二维码类型</label>
              <select v-model="qrType" class="input-field" @change="generateQRCode">
                <option value="text">文本</option>
                <option value="url">网址</option>
                <option value="email">邮箱</option>
                <option value="phone">电话号码</option>
                <option value="sms">短信</option>
                <option value="wifi">WiFi</option>
                <option value="vcard">名片</option>
              </select>
            </div>

            <!-- Size -->
            <div class="mb-6">
              <label class="block text-sm font-medium text-gray-700 mb-2">
                尺寸: {{ size }}px
              </label>
              <input
                v-model.number="size"
                type="range"
                min="100"
                max="500"
                step="50"
                class="w-full"
                @input="generateQRCode"
              >
              <div class="flex justify-between text-sm text-gray-500 mt-1">
                <span>100px</span>
                <span>500px</span>
              </div>
            </div>

            <!-- Error Correction Level -->
            <div class="mb-6">
              <label class="block text-sm font-medium text-gray-700 mb-2">纠错级别</label>
              <select v-model="errorCorrectionLevel" class="input-field" @change="generateQRCode">
                <option value="L">低 (~7%)</option>
                <option value="M">中 (~15%)</option>
                <option value="Q">四分之一 (~25%)</option>
                <option value="H">高 (~30%)</option>
              </select>
            </div>

            <!-- Colors -->
            <div class="grid grid-cols-2 gap-4 mb-6">
              <div>
                <label class="block text-sm font-medium text-gray-700 mb-2">前景色</label>
                <div class="flex items-center space-x-2">
                  <input
                    v-model="foregroundColor"
                    type="color"
                    class="w-12 h-12 rounded cursor-pointer"
                    @input="generateQRCode"
                  >
                  <input
                    v-model="foregroundColor"
                    type="text"
                    class="input-field flex-1"
                    @input="generateQRCode"
                  >
                </div>
              </div>
              <div>
                <label class="block text-sm font-medium text-gray-700 mb-2">背景色</label>
                <div class="flex items-center space-x-2">
                  <input
                    v-model="backgroundColor"
                    type="color"
                    class="w-12 h-12 rounded cursor-pointer"
                    @input="generateQRCode"
                  >
                  <input
                    v-model="backgroundColor"
                    type="text"
                    class="input-field flex-1"
                    @input="generateQRCode"
                  >
                </div>
              </div>
            </div>

            <!-- Action Buttons -->
            <div class="flex flex-wrap gap-3">
              <button @click="generateQRCode" class="primary-button" :disabled="!inputText">
                生成二维码
              </button>
              <button @click="downloadQRCode" class="secondary-button" :disabled="!qrCodeData">
                下载图片
              </button>
              <button @click="clearAll" class="secondary-button">
                清空内容
              </button>
              <button @click="loadSample" class="secondary-button">
                加载示例
              </button>
            </div>
          </div>

          <!-- Right Column: QR Code Display -->
          <div class="flex flex-col items-center">
            <div class="mb-4">
              <h3 class="text-lg font-semibold text-gray-900 mb-2">二维码预览</h3>
            </div>
            
            <div 
              class="bg-white border-2 border-gray-200 rounded-lg p-4 flex items-center justify-center"
              :style="{ width: size + 32 + 'px', height: size + 32 + 'px' }"
            >
              <div v-if="qrCodeData" class="text-center">
                <img 
                  :src="qrCodeData" 
                  :width="size" 
                  :height="size"
                  alt="QR Code"
                  class="border border-gray-300"
                >
              </div>
              <div v-else class="text-center text-gray-500">
                <svg class="w-16 h-16 mx-auto mb-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v1m6 11h2m-6 0h-2v4m0-11v3m0 0h.01M12 12h4.01M16 20h4M4 12h4m12 0h.01M5 8h2a1 1 0 001-1V5a1 1 0 00-1-1H5a1 1 0 00-1 1v2a1 1 0 001 1zm12 0h2a1 1 0 001-1V5a1 1 0 00-1-1h-2a1 1 0 00-1 1v2a1 1 0 001 1zM5 20h2a1 1 0 001-1v-2a1 1 0 00-1-1H5a1 1 0 00-1 1v2a1 1 0 001 1z"></path>
                </svg>
                <p>请输入内容生成二维码</p>
              </div>
            </div>

            <!-- QR Code Info -->
            <div v-if="qrCodeData" class="mt-4 text-center">
              <p class="text-sm text-gray-600">
                尺寸: {{ size }} × {{ size }} px
              </p>
              <p class="text-sm text-gray-600">
                纠错级别: {{ errorCorrectionLevel }}
              </p>
            </div>
          </div>
        </div>
      </div>

      <!-- Instructions -->
      <div class="mt-8 bg-white rounded-xl shadow-lg p-6">
        <h3 class="text-lg font-semibold text-gray-900 mb-4">使用说明</h3>
        <ul class="space-y-2 text-gray-600">
          <li>• 在输入框中输入要生成二维码的内容</li>
          <li>• 选择二维码类型（文本、网址、邮箱等）</li>
          <li>• 调整尺寸、纠错级别和颜色设置</li>
          <li>• 实时预览生成的二维码</li>
          <li>• 点击"下载图片"保存二维码到本地</li>
          <li>• 纠错级别越高，二维码可识别性越好，但容量越小</li>
        </ul>
      </div>

      <!-- QR Code Types Info -->
      <div class="mt-6 bg-white rounded-xl shadow-lg p-6">
        <h3 class="text-lg font-semibold text-gray-900 mb-4">二维码类型说明</h3>
        <div class="grid grid-cols-1 md:grid-cols-2 gap-4 text-sm text-gray-600">
          <div>
            <p><strong>文本：</strong>直接显示文本内容</p>
            <p><strong>网址：</strong>自动跳转到指定网站</p>
            <p><strong>邮箱：</strong>打开邮件客户端发送邮件</p>
            <p><strong>电话：</strong>拨打指定电话号码</p>
          </div>
          <div>
            <p><strong>短信：</strong>发送短信到指定号码</p>
            <p><strong>WiFi：</strong>连接到WiFi网络</p>
            <p><strong>名片：</strong>包含联系人信息的vCard</p>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, watch, onMounted } from 'vue'

const inputText = ref('')
const qrType = ref('text')
const size = ref(200)
const errorCorrectionLevel = ref('M')
const foregroundColor = ref('#000000')
const backgroundColor = ref('#ffffff')
const qrCodeData = ref('')

// 生成二维码（仅在浏览器端执行）
const generateQRCode = async () => {
  if (typeof window === 'undefined') return

  if (!inputText.value.trim()) {
    qrCodeData.value = ''
    return
  }

  try {
    // 根据类型格式化内容
    const formattedContent = formatContentByType(inputText.value, qrType.value)

    // 动态导入 qrcode（浏览器兼容）
    const mod = await import('qrcode')
    const QRCode = mod.default ?? mod

    const options = {
      width: size.value,
      height: size.value,
      color: {
        dark: foregroundColor.value,
        light: backgroundColor.value
      },
      errorCorrectionLevel: errorCorrectionLevel.value.toLowerCase()
    }

    // toDataURL 支持 promise 风格
    const url = await QRCode.toDataURL(formattedContent, options)
    qrCodeData.value = url
  } catch (error) {
    console.error('QR Code generation error:', error)
  }
}

// 根据二维码类型格式化内容
const formatContentByType = (content, type) => {
  switch (type) {
    case 'url':
      return content.startsWith('http') ? content : 'https://' + content
    case 'email':
      return `mailto:${content}`
    case 'phone':
      return `tel:${content}`
    case 'sms':
      return `smsto:${content}`
    case 'wifi':
      return `WIFI:T:WPA;S:${content};P:password;;`
    case 'vcard':
      return `BEGIN:VCARD\nVERSION:3.0\nFN:${content}\nEND:VCARD`
    default:
      return content
  }
}

// 下载二维码
const downloadQRCode = () => {
  if (!qrCodeData.value) return
  
  const link = document.createElement('a')
  link.download = `qrcode-${Date.now()}.png`
  link.href = qrCodeData.value
  link.click()
  
}

const clearAll = () => {
  inputText.value = ''
  qrCodeData.value = ''
}

const loadSample = () => {
  switch (qrType.value) {
    case 'url':
      inputText.value = 'https://example.com'
      break
    case 'email':
      inputText.value = 'example@email.com'
      break
    case 'phone':
      inputText.value = '+86 13800138000'
      break
    case 'text':
    default:
      inputText.value = 'Hello, World! 你好，世界！'
      break
  }
  generateQRCode()
}

// 监听输入变化，自动重新生成
// 将自动重生成移动到客户端挂载后，避免 SSR 时执行
onMounted(() => {
  watch([inputText, qrType, size, errorCorrectionLevel, foregroundColor, backgroundColor], () => {
    generateQRCode()
  }, { immediate: true })
})

// SEO
useHead({
  title: '二维码生成器 - 八八在线工具',
  meta: [
    { name: 'description', content: '在线二维码生成器，支持多种类型、自定义样式和尺寸，实时预览，一键下载' },
    { property: 'og:title', content: '二维码生成器 - 八八在线工具' },
    { property: 'og:description', content: '在线二维码生成器，支持多种类型、自定义样式和尺寸' }
  ]
})
</script>